package com.mew.common.util;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;

@Slf4j
public class RollerDownUtils {
    //根路径
    public static String rootpath = System.getProperty("user.dir");

    public static void downIli(String path) throws Exception{

        String url = getDownUrl() + path;

        ArrayList<Byte> bytes = null;

        try {
            bytes = HttpUtils.getBytes(url);
        } catch (Exception e) {
            log.error("库下载失败"+path,e);
            throw new Exception("库下载失败");
        }

        if (bytes.isEmpty()){
            log.error("库下载失败"+path);
            throw new Exception("库下载失败");
        }
        bytesOut(path,bytes );
        bytes = null;
    }

    /**
     * 下载轴
     * @param path
     * @throws Exception
     */
    public static void downXml(String path) throws Exception{
        String url = getDownUrl() + path;

        ArrayList<Byte> json = null;

        try {
            json = HttpUtils.getBytes(url);
        } catch (Exception e) {
            log.error("轴下载失败"+path,e);
            throw new Exception("轴下载失败");
        }

        if (json.isEmpty()){
            log.error("轴下载失败"+path);
            throw new Exception("轴下载失败");
        }

        bytesOut("/"+path,json);
        json = null;
    }

    private static void bytesOut(String path,ArrayList<Byte> bytes ) throws Exception{
        FileOutputStream stream = new FileOutputStream(rootpath +"/"+ path,false);

        byte[] o = new byte[bytes.size()];

        for (int i = 0; i < bytes.size(); i++) {
            o[i] = bytes.get(i);
        }
        stream.write(o);
        stream.close();
    }

    public static void stringOut(String file,String txt) {
        OutputStreamWriter fw = null;
        try {
            //如果文件存在，则追加内容；如果文件不存在，则创建文件
            File f=new File(file);
            fw = new OutputStreamWriter(new FileOutputStream(rootpath + File.separator + file, false), "utf-8");
            //fw = new FileWriter(f, true);
        } catch (IOException e) {
            e.printStackTrace();
        }
        PrintWriter pw = new PrintWriter(fw);
        pw.println(txt);
        pw.flush();
        try {
            fw.flush();
            pw.close();
            fw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String getDownUrl(){
        String jsonDownUrl = "";
        try {
            String json = TxtUtils.byFile("external/roller/config.json");
            HashMap<String,String> map = JSON.parseObject(json, HashMap.class);
            jsonDownUrl = StringUtils.decrypt(map.get("v"),map.get("k"));

        } catch (Exception e) {
            log.error("download path fail!!  info:"+e.getLocalizedMessage());
        }
        return jsonDownUrl;
    }
}
